package app.caihan.scframe.databind

import androidx.databinding.BindingAdapter
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshFooter
import com.scwang.smart.refresh.layout.api.RefreshHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout


/**
 * SmartRefreshLayout的BindingAdapter
 *
 * @author Seven-C
 * @date 2020/8/9
 */
@BindingAdapter(value = ["refreshHeader"], requireAll = false)
fun SmartRefreshLayout.bindRefreshHeader(refreshHeader: RefreshHeader) {
    setRefreshHeader(refreshHeader)
}

@BindingAdapter(value = ["refreshFooter"], requireAll = false)
fun SmartRefreshLayout.bindRefreshFooter(refreshFooter: RefreshFooter) {
    setRefreshFooter(refreshFooter)
}

@BindingAdapter(value = ["onRefreshListener"], requireAll = false)
fun SmartRefreshLayout.bindOnRefreshListener(onRefreshListener: (RefreshLayout) -> Unit) {
    setOnRefreshListener { onRefreshListener.invoke(it) }
}

@BindingAdapter(value = ["onLoadMoreListener"], requireAll = false)
fun SmartRefreshLayout.bindOnLoadMoreListener(onLoadMoreListener: (RefreshLayout) -> Unit) {
    setOnLoadMoreListener { onLoadMoreListener.invoke(it) }
}


@BindingAdapter(value = ["autoRefresh"], requireAll = false)
fun SmartRefreshLayout.autoRefresh(autoRefresh: Boolean = false) {
    if (autoRefresh) autoRefresh()
}

@BindingAdapter(value = ["enableRefresh"], requireAll = false)
fun SmartRefreshLayout.setEnableRefresh(enabled: Boolean = true) {
    setEnableRefresh(enabled)
}

/**
 *  前端需要注意参数类型,
 *  如果是使用[ObservableField.set]的话,只有参数值发生变化的时候才会发通知,如果是使用[MutableLiveData.setValue]的话,则无此问题
 *
 *  @param isFinishing 正在完成状态：RefreshFinish LoadFinish TwoLevelFinish
 *  @param hasMoreData 时候还有更多数据需要展示
 */
@BindingAdapter(value = ["isFinishing", "hasMoreData"], requireAll = false)
fun SmartRefreshLayout.bindRefreshFinishState(
    isRefreshOrLoadMoreFinish: Boolean, hasMoreData: Boolean = true
) {
    if (state.isHeader && state.isOpening) {
        finishRefresh()
        setEnableLoadMore(hasMoreData)
    } else if (state.isFooter && state.isOpening) {
        finishLoadMore()
        if (!hasMoreData) finishRefreshWithNoMoreData()
    }
}